<template>
  <!--完成确认弹窗-->
  <px-dialog v-model="visible" title="审核" width="600px" destroy-on-close append-to-body @close="handleCancelAudit">
    <px-form ref="auditRef" :model="auditForm" :rules="rules" label-width="100px">
      <px-form-item label="审核人员" prop="operateName">
        <px-input v-model="auditForm.operateName" disabled />
      </px-form-item>
      <px-form-item label="审核结果" prop="approvalResult">
        <px-select v-model="auditForm.approvalResult" style="width: 100%" placeholder="请选择" clearable>
          <px-option v-for="item in optionsList" :key="item.value" :label="item.label" :value="item.value" />
        </px-select>
      </px-form-item>
      <px-form-item label="审核意见" prop="approvalOpinion">
        <px-input v-model="auditForm.approvalOpinion" maxlength="1000" type="textarea" placeholder="请输入" />
      </px-form-item>
    </px-form>
    <template #footer>
      <div class="dialog-footer">
        <px-button @click="handleCancelAudit">取消</px-button>
        <px-button type="primary" @click="handleSubmitAuditForm(auditRef)">确认</px-button>
      </div>
    </template>
  </px-dialog>
</template>

<script lang="ts" setup>
import { auditMaintainList, getApprovalStatusList } from "@/api/erc/maintain";
import { PxMessage } from "px-ui";
import { computed, onMounted, reactive, ref, toRefs, watchEffect } from "vue";

// 调用父级-返回主页、查询列表方法
const emits = defineEmits(["closeDialog", "queryTable"]);
// 父级传过来的值
const props = defineProps(["visible", "isAudit", "taskId"]);

const visible = computed(() => props.visible);

// 表单校验规则
const rules = computed(() => ({
  approvalResult: [{ required: true, message: "请选择审核结果", trigger: ["blur", "change"] }],
  approvalOpinion: [{ required: auditForm.value.approvalResult !== "pass", message: "请填写审核意见", trigger: ["blur", "change"] }]
}));

const auditRef = ref();
const optionsList = ref([]);

const state = reactive<Record<string, any>>({
  auditForm: {}
});
const { auditForm } = toRefs(state);

const handleCancelAudit = () => {
  auditRef.value.resetFields();
  emits("closeDialog");
};
const initOptionsList = async () => {
  const data = await getApprovalStatusList();
  optionsList.value = data?.map(item => ({ ...item, label: item.name }));
};
onMounted(() => {
  initOptionsList();
});
watchEffect(async () => {
  if (props.visible) {
    const userInfo = JSON.parse(localStorage.getItem("userInfo"));
    auditForm.value.operateName = userInfo.realName;
    auditForm.value.operateId = userInfo.userId;
  }
});

/** 提交按钮 */
const handleSubmitAuditForm = async (formEl: any) => {
  if (!formEl) return;
  await formEl.validate(async valid => {
    if (valid) {
      await auditMaintainList({ busId: props.taskId, ...auditForm.value });
      PxMessage.success("审核成功");
      handleCancelAudit();
      emits("queryTable");
    }
  });
};
</script>
